$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone',
        $search = $('.search'),
        $searchBar = $('.search-btn'),
        $export = $('.search-export'),
        total_number = 0, can_send_total_number = 0;
    var config = {
        query: '/order/queryWithOffer?type1=exchange',//分页查询URL,

    }, operator_list = [], operate = {}, list;
    $searchBar.click(function () {
        $(this).button('loading');
        console.log({
            page: 1,
            checkStatus: $('[name=checkStatus]').val(),
            deliverStatus: $('[name=deliverStatus]').val(),
            payStatus: $('[name=payStatus]').val(),
            goodsId: $('[name=goodsId]').val(),
            status: $('[name=status]').val(),
            clienteleName: $('[name=clienteleName]').val(),
            no: $('[name=no]').val(),
        });
        search({
            page: 1,
            checkStatus: $('[name=checkStatus]').val(),
            deliverStatus: $('[name=deliverStatus]').val(),
            payStatus: $('[name=payStatus]').val(),
            goodsId: $('[name=goodsId]').val(),
            status: $('[name=status]').val(),
            clienteleName: $('[name=clienteleName]').val(),
            no: $('[name=no]').val(),
        });
    });
    $('[name=clienteleName]').on('keypress', function (e) {
        if (e.keyCode == 13) {
            $searchBar.click();
        }
    });

    var searchObj = parseSearch();
    if (searchObj.type == 'ongoing' || searchObj.type == 'order') { // 正在进行的拼团或已完成的拼团
        config.query = '/order/queryGroup?status=' + (searchObj.type == 'ongoing' ? '1' : '2')//
    }


    $('[name=startDate]').datepicker({
        todayHighlight: true,
        autoclose: true,
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        size: 'small',
    });
    $('[name=endDate]').datepicker({
        todayHighlight: true,
        autoclose: true,
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        size: 'small',
    });
    $('[name=no]').on('keypress', function (e) {
        if (e.keyCode == 13) {
            $searchBar.click();
        }
    });


    /**
     * @param obj
     * @returns {*|{opacity}}
     */
    function search(obj, isForce, isExport) {

        return gSearch({
            url: config.query,
            query: obj || {},
            render: render,
            isForce: isForce,
            isExport: isExport
        }, obj.first ? false : true);
        var query_ = {
            startDate: $('[name=startDate]').val(),
            endDate: $('[name=endDate]').val(),
        };
        query_ = $.extend({}, query, query_, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return;
            }
        }
        var arg = [];
        query = query_;
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            if ((query_[key] + '').length) {
                arg.push(key + '=' + query_[key])
            }
        });
        query = query_;
        query.timestamp = Date.now();
        if (isExport) {
            return config.query + arg.join('&');
        }
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.code != 200) {
                return alert(res.error);
            }
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page, query, search)

        });
    }

    $export.unbind('click').click(function () {
        generateExportUrl(search({}, true, true));
    });
    $.get(config.query_store, function (data) {
        if (data.code == 200) {
            list = data.list;
            operator_list = data.list;
            render_operators();
        }
    });
    function render_operators(initData) {
        initData = initData || '';
        $('.select_multi .panel-body .stores').html('');
        operator_list.map(function (item, index) {
            $('.select_multi .panel-body .stores').append('<label class="radio-inline" style="margin: 0;padding-right: 15px;"> \
                <input type="radio"  name="storeId" class="operate_item" data-value="' + item.name + '"  value="' + item.id + '"> ' + item.name + ' \
                </label>')
        });
        $('[name=storeId]').click(function (e) {
            $('[name=deliverPlace]').val($(this).attr('value'));
            $('[name=deliverPlace]').data('id', $(this).val());
        });
    }

    $('[name=payStatus]').change(function () {
        search({
            page: 1,
            payStatus: $('[name=payStatus]').val(),
        })
    });
    $('[name=deliverStatus]').change(function () {
        search({
            page: 1,
            deliverStatus: $('[name=deliverStatus]').val(),
        })
    });


    function render(list) {
        $('.table-responsive .table tbody').html('');
        var fields = [
            {
                name: 'no', label: '订单号', filter: function (item) {
                return '<a href="javascript:void(0)"  title="查看订单详情"  class="detail" data-href="./detail.html?id=' + item.id + '">' + item.no + '</a>'
            }
            },
            {name: 'varsName', label: '商品名称'},
            {
                name: 'status', label: '状态',
                filter: function (item) {
                    return orderStatus(item.status).text;
                }
            },
            {
                name: 'status', label: '付款/发货/审核状态',
                filter: function (item) {
                    return (item.payStatus == 0 ? '未付款' : (item.payStatus == 1 ? '已付款' : '未付款')) + '/' + (item.deliverStatus == 0 ? '<span class="label label-danger">未发货</span>' : (item.deliverStatus == 1 ? '<span class="label label-warning">已发货</span>' : (item.deliverStatus == 2 ? '<span class="label label-success">已收货</span>' : '')));
                }
            },
            {
                name: 'number', label: '数量',
                filter: function (item) {
                    return number_format(item.number, 3);
                }
            },
            {
                name: 'number', label: '兑换积分',
                filter: function (item) {
                    return number_format(item.actualTotal, 2);
                }
            },
            {
                name: 'createAt', label: '兑换时间',
                filter: function (item) {
                    return (moment(item.createAt).format('YYYY-MM-DD HH:mm:ss'));
                }
            },
        ];
        if (searchObj.type == 'ongoing' || searchObj.type == 'order') {
            fields = [
                {
                    name: 'en', label: '拼团号',
                    filter: function (item) {
                        return '<a href="javascript:void(0);" class="group-detail" data-id="' + item.id + '"  data-href="./group-detail.html?id=' + item.id + '">' + item.en + '</a>';
                    }
                },
                {
                    name: 'desc1', label: '拼团主题',
                    filter: function (item) {
                        return item.desc1;
                    }
                },
                {
                    name: 'status', label: '拼团状态',
                    filter: function (item) {
                        return item.status = '1' ? '<span class="label label-warning">拼团中</span>' : (item.status = '2' ? '<span class="label label-success">完成拼团</span>' : (item.status = '3' ? '<span class="label-default">取消拼团</span>' : ''))
                    }
                },
                {name: 'level', label: '参团人数'},
                {
                    name: 'total', label: '几人团', filter: function (item) {
                    return parseInt(item.total);
                }
                },
                {
                    name: 'validStart', label: '发起拼团开始时间', filter: function (item) {
                    return formatTime(item.validStart);
                }
                },
                {
                    name: 'validEnd', label: '发起拼团截止时间', filter: function (item) {
                    return formatTime(item.validEnd);
                }
                },
                {
                    name: 'validEnd', label: '剩余时间', filter: function (item) {
                    return formatDuring(item.validEnd - new Date().getTime());
                }
                },
            ]
        }

        if (list instanceof Array) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                rendered: function () {
                    onClick($('.group-detail'), function () {
                        layerAlert({
                            type: 2,
                            full: true,
                            body: [$(this).data('href')],
                            title: '拼团详情：' + $(this).html()
                        })
                    })
                    onClick($('.detail'), function () {
                        console.log($(this).data('href'));
                        layerAlert({
                            type: 2,
                            full: true,
                            body: [$(this).data('href')],
                            title: '订单详情：' + $(this).html()
                        })
                    });
                },
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: fields,
                data: list || [],
            }));
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }


    function total_change() {
        var total = 0;
        $('.orders-list-to-send input[type=checkbox]:checked').each(function (index, item) {
            if ($(item).is(':checked')) {
                total = floatTool.add(total, parseFloat($(item).closest('tr').find('input[type=number]').val()));
            }
        });
        $('.thisTimeNumber-label').html(total);
        $('[name=numberThisTime]').val(total);
    }

    function getRelatedOrder(item) {
        $.get(config.getRelatedOrder + '?clienteleId=' + item.clienteleId + '&offerId=' + item.offerId + '&checkStatus=1', function (xhr) {
            if (xhr.code == 200) {
                if (xhr.list.length > 1) {
                    xhr.list.map(function (ite) {
                        var total = ite.number - ite.deliverNumber;
                        if (ite.id != item.id && total > 0) {
                            $('.selected-order').append('<tr> \
                        <td class=""><div class="more-detail"></div><input type="checkbox"  data-id="' + ite.id + '"  data-pay="' + ite.payStatus + '"  data-json=\'' + JSON.stringify(ite) + '\' /><i class="fa fa-angle-double-down" aria-hidden="true"></i></td>  \
                            <td>' + ite.no + '</td><td style="width: 55px;">' + total + '</td><td>' + moment(ite.createAt).format('YYYY/MM/DD HH:mm:ss') + '</td> \
                            <td><input type="text"  class="form-control batch-no input-batch" placeholder="进货批号"/></td> \
                        <td><input type="number" max="' + total + '" class="form-control" disabled value="' + total + '"/></td> \
                            </tr>')
                        }
                    });

                    $('.load-orders').hide();
                    // $('.combine-orders').find('input[type=number]').change(function () {
                    //     canSendNumTotal();
                    // });
                    getSendTotal();
                    $('.selected-order').find('input[type=checkbox]').click(function () {
                        var $item = $(this).data('json');
                        if ($(this).is(":checked")) {
                            $(this).closest('tr').find('input[type=number]').attr('disabled', false).prop('disabled', false);
                            total_number = math.chain(total_number).add($item.number).subtract($item.deliverNumber);
                        } else {
                            $(this).closest('tr').find('input[type=number]').attr('disabled', true).prop('disabled', true);
                            total_number = math.chain(total_number).subtract($item.number).add($item.deliverNumber);
                            // total_number -= $item.number - $item.deliverNumber;
                        }
                        canSendNumTotal();

                    })

                } else {
                    $('.load-orders').html('该订单暂无可合并发货的订单!').removeClass('btn btn-inf');
                    $('.load-orders').hide();
                }
            }
        })
    }

    /**
     *累计可发货数量
     */
    function canSendNumTotal() {
        $('.thisTimeTotal-label').html(total_number);
        total_change();
    }

    search({first: true}, true);
    $('.order-check').on('show', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('json');
        console.log(recipient);
        var modal = $(this);
        $('.hp-refuse').val(''); // 审核
        modal.find('.modal-title').text('审核订单');
        modal.find('.modal-title').data('id', recipient.id);
    }).on('okHide', function (event) {

        var $id = $(event.target).closest('.modal-content').find('.modal-title').data('id');
        if ($(event.target).text().indexOf('通过') > -1) {
            var $refuse = $('.hp-refuse');
            $.post(config.check, {
                id: $id,
                checkStatus: 1,
                reason: $refuse.val()
            }, function (data) {
                if (data.code == 200) {
                    search({}, true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        } else if ($(event.target).text().indexOf('拒绝') > -1) {
            var $refuse = $('.hp-refuse');
            if (!$refuse.val()) {
                $refuse.addClass('hp-input-error');
                fnFail("请填写原因？");
                return false;
            } else {
                $refuse.removeClass('hp-input-error');
            }
            $.post(config.check, {
                id: $id,
                checkStatus: 2,
                reason: $refuse.val()
            }, function (data) {
                if (data.code == 200) {
                    search({}, true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        }
        return false;
    });
    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

});